<!DOCTYPE html>
<html lang="zh-CN,en,zh-HK,zh-TW,default">
<head hexo-theme='https://github.com/volantis-x/hexo-theme-volantis/tree/4.0.0'>
  <meta charset="utf-8">
  <!-- SEO相关 -->
  
    
  
  <!-- 渲染优化 -->
  <meta name="renderer" content="webkit">
  <meta name="force-rendering" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="HandheldFriendly" content="True" >
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta http-equiv='x-dns-prefetch-control' content='on' />

  <!-- 页面元数据 -->
  
  <title>第六章 C控制语句：循环 - HardyDragon Index</title>
  
    <meta name="keywords" content="C Notes">
  

  

  <!-- feed -->
  

  <!-- import meta -->
  
    
      <meta name="msapplication-TileColor" content="#ffffff">
    
      <meta name="msapplication-config" content="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/browserconfig.xml">
    
      <meta name="theme-color" content="#ffffff">
    
  

  <!-- link -->
  <link rel='dns-prefetch' href='https://cdn.jsdelivr.net'>
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.14/css/all.min.css">

  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css">

  

  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.css">

  

  

  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer@1.10/dist/APlayer.min.css">
  

  

  <!-- import link -->
  
  
  <link rel="apple-touch-icon" sizes="180x180" href="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="https://s1.ax1x.com/2020/10/02/0l3pPe.png">
  <link rel="icon" type="image/png" sizes="16x16" href="https://s1.ax1x.com/2020/10/02/0l3pPe.png">
  <link rel="manifest" href="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/site.webmanifest">
  <link rel="mask-icon" href="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/safari-pinned-tab.svg" color="#5bbad5">
  <link rel="shortcut icon" href="https://s1.ax1x.com/2020/10/02/0l3pPe.png">
  

  
    
      
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.18.1/styles/solarized-light.css">

    
  
  
    
<link rel="stylesheet" href="/blog/css/style.css">

  
  
  
  <!-- 脚本懒加载函数 -->
  <script>
  function loadScript(src, cb) {
    var HEAD = document.getElementsByTagName('head')[0] || document.documentElement;
    var script = document.createElement('script');
    script.setAttribute('type','text/javascript');
    if (cb) script.onload = cb;
    script.setAttribute('src', src);
    HEAD.appendChild(script);
  }
  //https://github.com/filamentgroup/loadCSS
  !function(c){"use strict";var e=function(e,t,n,r){var o,i=c.document,a=i.createElement("link");if(t)o=t;else{var d=(i.body||i.getElementsByTagName("head")[0]).childNodes;o=d[d.length-1]}var f=i.styleSheets;if(r)for(var l in r)r.hasOwnProperty(l)&&a.setAttribute(l,r[l]);a.rel="stylesheet",a.href=e,a.media="only x",function e(t){if(i.body)return t();setTimeout(function(){e(t)})}(function(){o.parentNode.insertBefore(a,t?o:o.nextSibling)});var s=function(e){for(var t=a.href,n=f.length;n--;)if(f[n].href===t)return e();setTimeout(function(){s(e)})};function u(){a.addEventListener&&a.removeEventListener("load",u),a.media=n||"all"}return a.addEventListener&&a.addEventListener("load",u),(a.onloadcssdefined=s)(u),a};"undefined"!=typeof exports?exports.loadCSS=e:c.loadCSS=e}("undefined"!=typeof global?global:this);
  </script>
  <script id="loadcss"></script>
</head>

<body>
  <header class="l_header always shadow blur "  >
  <div class='container'>
  <div class='wrapper'>
    <div class='nav-sub'>
      <p class="title"></p>
      <ul class='switcher nav-list-h m-phone' id="pjax-header-nav-list">
        <li><a class="s-comment fas fa-comments fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
          <li><a class="s-toc fas fa-list fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
      </ul>
    </div>
		<div class="nav-main">
      
        
        <a class="title flat-box" target="_self" href='/blog/'>
          
          
            <i class='https://s1.ax1x.com/2020/10/02/0l3pPe.png'></i>
          
          
            HardyDragon
          
        </a>
      

			<div class='menu navigation'>
				<ul class='nav-list-h m-pc'>
          
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/
                  
                  
                  
                    id="blog"
                  >
                  <i class='fas fa-rss fa-fw'></i>博客
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/categories/
                  
                  
                  
                    id="blogcategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/tags/
                  
                  
                  
                    id="blogtags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/archives/
                  
                  
                  
                    id="blogarchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/friends/
                  
                  
                  
                    id="blogfriends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/about/
                  
                  
                  
                    id="blogabout"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://blog.csdn.net/qq_44880154
                  
                  
                  
                    id="https:blogcsdnnetqq_44880154"
                  >
                  <i class='fas fa-fire fa-fw'></i>CSDN
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://gitee.com/hardychenlong
                  
                  
                  
                    id="https:giteecomhardychenlong"
                  >
                  <i class='fas fa-clock fa-fw'></i>gitee
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  <i class='fas fa-ellipsis-v fa-fw'></i>更多
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantis"
                  >
                  主题源码
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/releases/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantisreleases"
                  >
                  更新日志
                </a>
                
              </li>
            
          
                    
                      
            
              <hr>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  有疑问？
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/faqs/
                  
                  
                  
                    id="blogfaqs"
                  >
                  看 FAQ
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/volantis-docs/
                  
                  
                  
                    id="https:githubcomvolantis-xvolantis-docs"
                  >
                  看 本站源码
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/issues/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantisissues"
                  >
                  提 Issue
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
                    
                      
            
              <hr>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/archives/
                  
                  
                  
                    id="blogarchives"
                  >
                  公告和测试博文
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/examples/
                  
                  
                  
                    id="blogexamples"
                  >
                  示例博客
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/contributors/
                  
                  
                  
                    id="blogcontributors"
                  >
                  特别感谢
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
				</ul>
			</div>

      <div class="m_search">
        <form name="searchform" class="form u-search-form">
          <i class="icon fas fa-search fa-fw"></i>
          <input type="text" class="input u-search-input" placeholder="搜索" />
        </form>
      </div>

			<ul class='switcher nav-list-h m-phone'>
				
					<li><a class="s-search fas fa-search fa-fw" target="_self" href='javascript:void(0)'></a></li>
				
				<li>
          <a class="s-menu fas fa-bars fa-fw" target="_self" href='javascript:void(0)'></a>
          <ul class="menu-phone list-v navigation white-box">
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/
                  
                  
                  
                    id="blog"
                  >
                  <i class='fas fa-rss fa-fw'></i>博客
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/categories/
                  
                  
                  
                    id="blogcategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/tags/
                  
                  
                  
                    id="blogtags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/archives/
                  
                  
                  
                    id="blogarchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/friends/
                  
                  
                  
                    id="blogfriends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/about/
                  
                  
                  
                    id="blogabout"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://blog.csdn.net/qq_44880154
                  
                  
                  
                    id="https:blogcsdnnetqq_44880154"
                  >
                  <i class='fas fa-fire fa-fw'></i>CSDN
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://gitee.com/hardychenlong
                  
                  
                  
                    id="https:giteecomhardychenlong"
                  >
                  <i class='fas fa-clock fa-fw'></i>gitee
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  <i class='fas fa-ellipsis-v fa-fw'></i>更多
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantis"
                  >
                  主题源码
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/releases/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantisreleases"
                  >
                  更新日志
                </a>
                
              </li>
            
          
                    
                      
            
              <hr>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  有疑问？
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/faqs/
                  
                  
                  
                    id="blogfaqs"
                  >
                  看 FAQ
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/volantis-docs/
                  
                  
                  
                    id="https:githubcomvolantis-xvolantis-docs"
                  >
                  看 本站源码
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/issues/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantisissues"
                  >
                  提 Issue
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
                    
                      
            
              <hr>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/archives/
                  
                  
                  
                    id="blogarchives"
                  >
                  公告和测试博文
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/examples/
                  
                  
                  
                    id="blogexamples"
                  >
                  示例博客
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/contributors/
                  
                  
                  
                    id="blogcontributors"
                  >
                  特别感谢
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
          </ul>
        </li>
			</ul>
		</div>
	</div>
  </div>
</header>

  <div class="l_body">
    <div class="l_cover">
  
    
    
        <div class='cover-wrapper post dock' style="display: none;">
          
            <div class='cover-backstretch'></div>
          
          <div class='cover-body'>
  <div class='top'>
    
    
      <p class="title">HardyDragon</p>
    
    
  </div>
  <div class='bottom'>
    <div class='menu navigation'>
      <div class='list-h'>
        
          
            <a target="_blank" rel="noopener" href="https://gitee.com/hardychenlong"
              
              
              id="https:giteecomhardychenlong">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f5c3.svg'><p>Gitee</p>
            </a>
          
            <a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_44880154"
              
              
              id="https:blogcsdnnetqq_44880154">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f516.svg'><p>CSDN</p>
            </a>
          
            <a target="_blank" rel="noopener" href="https://volantis.js.org/examples/"
              
              
              id="https:volantisjsorgexamples">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f396.svg'><p>示例</p>
            </a>
          
            <a target="_blank" rel="noopener" href="https://volantis.js.org/examples/"
              
              
              id="https:volantisjsorgexamples">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f389.svg'><p>社区</p>
            </a>
          
            <a href="/blog/archives/"
              
              
              id="blogarchives">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f4f0.svg'><p>博客</p>
            </a>
          
            <a target="_blank" rel="noopener" href="https://github.com/volantis-x/hexo-theme-volantis/"
              
              
              id="https:githubcomvolantis-xhexo-theme-volantis">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f9ec.svg'><p>源码</p>
            </a>
          
        
      </div>
    </div>
  </div>
</div>

          <div class="scroll-down" style="display: none;"><i class="fa fa-chevron-down scroll-down-effects"></i></div>
        </div>
    
  
  </div>
  
    <div class='safearea'>
      <div class='body-wrapper' id="pjax-container">
        
          <!--此文件用来存放一些不方便取值的变量--> 
<!--思路大概是将值藏到重加载的区域内--> 
 
 
 
<div id="pjax-data" style="display: none"> 
  <div id="pjax-ispage">true</div> 
  <div id="pjax-pageTitle">第六章 C控制语句：循环</div> 
  <div id="pjax-enable-cover">true</div> 
  <div id="pjax-comment-path"></div> 
  <div id="pjax-comment-placeholder"></div> 
</div> 
 
 
<script> 
  // 处理封面 此时 jquery 还没加载 
  if ("none" == "none") { // 移除封面 
    document.getElementsByClassName('cover-wrapper')[0].style.display = "none"; 
    document.getElementsByClassName('l_header', 'cover-wrapper')[0].classList.add("show"); 
  } else { 
    if ("none" == "half") { // 半屏 
      document.getElementsByClassName('cover-wrapper')[0].setAttribute('id', 'half'); 
      document.getElementsByClassName('scroll-down')[0].style.display = "none"; 
    } else if ("none" == "full") { // 全屏 
      document.getElementsByClassName('cover-wrapper')[0].setAttribute('id', 'full'); 
      document.getElementsByClassName('scroll-down')[0].style.display = ""; 
    } 
    document.getElementsByClassName('cover-wrapper')[0].style.display = ""; 
    document.getElementsByClassName('l_header', 'cover-wrapper')[0].classList.remove("show"); 
  } 
</script> 
 

        
        

<div class='l_main'>
  <article class="article post white-box reveal md shadow article-type-post" id="post" itemscope itemprop="blogPost">
  


  
  <div class="article-meta" id="top">
    
    
    
      <h1 class="title">
        第六章 C控制语句：循环
      </h1>
      <div class='new-meta-box'>
        
          
            
<div class='new-meta-item author'>
  <a class='author' href="/" rel="nofollow">
    <img no-lazy src="">
    <p>请设置文章作者</p>
  </a>
</div>

          
        
          
            

          
        
          
            <div class="new-meta-item date">
  <a class='notlink'>
    <i class="fas fa-calendar-alt fa-fw" aria-hidden="true"></i>
    <p>发布于：2021年3月22日</p>
  </a>
</div>

          
        
          
            
  <div class="new-meta-item browse leancloud">
    <a class='notlink'>
      
      <div id="lc-pv" data-title="第六章 C控制语句：循环" data-path="/blog/2021/03/22/%E7%AC%AC%E5%85%AD%E7%AB%A0C%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%BE%AA%E7%8E%AF/">
        <i class="fas fa-eye fa-fw" aria-hidden="true"></i>
        <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span>
        次浏览
      </div>
    </a>
  </div>


          
        
      </div>
    
  </div>


  
  <h1 id="第六章-C控制语句：循环"><a href="#第六章-C控制语句：循环" class="headerlink" title="第六章 C控制语句：循环"></a>第六章 C控制语句：循环</h1><h2 id="6-1-再探while循环"><a href="#6-1-再探while循环" class="headerlink" title="6.1 再探while循环"></a><a href="#6.1">6.1 再探while循环</a></h2><h3 id="程序注释"><a href="#程序注释" class="headerlink" title="程序注释"></a>程序注释</h3><h3 id="C风格读取循环"><a href="#C风格读取循环" class="headerlink" title="C风格读取循环"></a>C风格读取循环</h3><h2 id="6-2-while语句"><a href="#6-2-while语句" class="headerlink" title="6.2 while语句"></a><a href="#6.2">6.2 while语句</a></h2><h3 id="6-2-1-终止while循环"><a href="#6-2-1-终止while循环" class="headerlink" title="6.2.1 终止while循环"></a>6.2.1 终止while循环</h3><h3 id="何时终止循环"><a href="#何时终止循环" class="headerlink" title="何时终止循环"></a>何时终止循环</h3><h3 id="while：入口条件循环"><a href="#while：入口条件循环" class="headerlink" title="while：入口条件循环"></a>while：入口条件循环</h3><h3 id="语法要点"><a href="#语法要点" class="headerlink" title="语法要点"></a>语法要点</h3><h2 id="6-3-用关系运算符和表达式比较大小"><a href="#6-3-用关系运算符和表达式比较大小" class="headerlink" title="6.3 用关系运算符和表达式比较大小"></a><a href="#6.3">6.3 用关系运算符和表达式比较大小</a></h2><h3 id="6-3-1-什么是真"><a href="#6-3-1-什么是真" class="headerlink" title="6.3.1 什么是真"></a>6.3.1 什么是真</h3><h3 id="6-3-2-其他真值"><a href="#6-3-2-其他真值" class="headerlink" title="6.3.2 其他真值"></a>6.3.2 其他真值</h3><h3 id="6-3-3-真值的问题"><a href="#6-3-3-真值的问题" class="headerlink" title="6.3.3 真值的问题"></a>6.3.3 真值的问题</h3><h3 id="6-3-4-新的-Bool-类型"><a href="#6-3-4-新的-Bool-类型" class="headerlink" title="6.3.4 新的_Bool 类型"></a>6.3.4 新的_Bool 类型</h3><h3 id="6-3-5-优先级和关系运算符"><a href="#6-3-5-优先级和关系运算符" class="headerlink" title="6.3.5 优先级和关系运算符"></a>6.3.5 优先级和关系运算符</h3><h2 id="6-4-不确定循环和计数循环"><a href="#6-4-不确定循环和计数循环" class="headerlink" title="6.4 不确定循环和计数循环"></a><a href="#6.4">6.4 不确定循环和计数循环</a></h2><h2 id="6-5-for循环"><a href="#6-5-for循环" class="headerlink" title="6.5 for循环"></a><a href="#6.5">6.5 for循环</a></h2><h2 id="6-6-其他赋值运算符：-、-、-、-、"><a href="#6-6-其他赋值运算符：-、-、-、-、" class="headerlink" title="6.6 其他赋值运算符： += 、-=、*=、/=、%="></a><a href="#6.6">6.6 其他赋值运算符： += 、-=、*=、/=、%=</a></h2><h2 id="6-7-逗号运算符"><a href="#6-7-逗号运算符" class="headerlink" title="6.7 逗号运算符"></a><a href="#6.7">6.7 逗号运算符</a></h2><h2 id="6-8-出口条件循环：do-while"><a href="#6-8-出口条件循环：do-while" class="headerlink" title="6.8 出口条件循环：do while"></a><a href="#6.8">6.8 出口条件循环：do while</a></h2><h2 id="6-9-如何选择循环"><a href="#6-9-如何选择循环" class="headerlink" title="6.9 如何选择循环"></a><a href="#6.9">6.9 如何选择循环</a></h2><h2 id="6-10-嵌套循环"><a href="#6-10-嵌套循环" class="headerlink" title="6.10 嵌套循环"></a><a href="#6.10">6.10 嵌套循环</a></h2><h3 id="6-10-1-程序分析"><a href="#6-10-1-程序分析" class="headerlink" title="6.10.1 程序分析"></a>6.10.1 程序分析</h3><h3 id="6-10-2-嵌套变式"><a href="#6-10-2-嵌套变式" class="headerlink" title="6.10.2 嵌套变式"></a>6.10.2 嵌套变式</h3><h2 id="6-11-数组简介"><a href="#6-11-数组简介" class="headerlink" title="6.11 数组简介"></a><a href="#6.11">6.11 数组简介</a></h2><h2 id="6-12-使用函数返回值的循环示例"><a href="#6-12-使用函数返回值的循环示例" class="headerlink" title="6.12 使用函数返回值的循环示例"></a><a href="#6.12">6.12 使用函数返回值的循环示例</a></h2><h3 id="6-12-1-程序分析"><a href="#6-12-1-程序分析" class="headerlink" title="6.12.1 程序分析"></a>6.12.1 程序分析</h3><h3 id="6-12-2-使用带返回值的函数"><a href="#6-12-2-使用带返回值的函数" class="headerlink" title="6.12.2 使用带返回值的函数"></a>6.12.2 使用带返回值的函数</h3><h2 id="6-13-关键概念"><a href="#6-13-关键概念" class="headerlink" title="6.13 关键概念"></a><a href="#6.13">6.13 关键概念</a></h2><h2 id="6-14-本章小结"><a href="#6-14-本章小结" class="headerlink" title="6.14 本章小结"></a><a href="#6.14">6.14 本章小结</a></h2><h2 id="6-15-复习题"><a href="#6-15-复习题" class="headerlink" title="6.15 复习题"></a><a href="#6.15">6.15 复习题</a></h2><h2 id="6-16-编程练习"><a href="#6-16-编程练习" class="headerlink" title="6.16 编程练习"></a><a href="#6.16">6.16 编程练习</a></h2><hr>
<p><a name="6.1">6.1 再探while循环</a></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// summing.c -- 根据用户输入的整数求和</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">long</span> num;</span><br><span class="line">    <span class="keyword">long</span> sum = <span class="number">0L</span>;</span><br><span class="line">    <span class="keyword">int</span> status;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;please enter an integer to be sum(Q to quit):\n&quot;</span>);</span><br><span class="line">    status = <span class="built_in">scanf</span>(<span class="string">&quot;%ld&quot;</span>, &amp;num);</span><br><span class="line">    <span class="keyword">while</span> (status == <span class="number">1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* code */</span></span><br><span class="line">        sum = sum + num;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;please enter an integer to be sum(Q to quit):\n&quot;</span>);</span><br><span class="line">        status = <span class="built_in">scanf</span>(<span class="string">&quot;%ld&quot;</span>, &amp;num);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;sum is %ld\n&quot;</span>,sum);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">please enter an integer to be sum(Q to quit):</span><br><span class="line">44</span><br><span class="line">please enter an integer to be sum(Q to quit):</span><br><span class="line">33</span><br><span class="line">please enter an integer to be sum(Q to quit):</span><br><span class="line">88</span><br><span class="line">please enter an integer to be sum(Q to quit):</span><br><span class="line">121</span><br><span class="line">please enter an integer to be sum(Q to quit):</span><br><span class="line">q</span><br><span class="line">sum is 286</span><br></pre></td></tr></table></figure>

<p>该程序使用long类型以存储更大的整数，尽管C编译器会把0自动转换为合适的类型，但是为了保持程序的一致性，把sum初始化为0L，而不是0（int类型的0）；<br>回顾一下，scanf() 的返回值若成功读取一个整数，就将读取的数放入变量，并返回1。如果输入的类型匹配失败就返回0；如果scanf() 在转换值前出现了问题会返回一个特殊值EOF（-1），这个也会导致循环终止。<br>因为while循环时入口条件循环，程序在进入循环体前必须获取输入的数据并检查status的值，所以while前面要有一个scanf() ，要让循环继续执行，在循环内需要一个读取数据的语句，这样程序才能获取下一个status的值，所以scanf() 函数末尾还要有一个scanf() 它为下一次迭代做好了准备。</p>
<ul>
<li><p>C风格的读取循环</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">status = <span class="built_in">scanf</span>(<span class="string">&quot;%ld&quot;</span>, &amp;num);</span><br><span class="line"><span class="keyword">while</span> (status == <span class="number">1</span>)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* code */</span></span><br><span class="line">    status = <span class="built_in">scanf</span>(<span class="string">&quot;%ld&quot;</span>,&amp;num);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>以上读取循环输入的代码可以写的更简洁</strong>：（相当于省略中间变量status）</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> (<span class="built_in">scanf</span>(<span class="string">&quot;%ld&quot;</span>, &amp;num) == <span class="number">1</span>)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* code */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p><a name="6.2">6.2 while语句</a></p>
<p>关于终止while循环要注意其条件语句，最小负值减1一般会得到最大值，最大值加1会得到一个负值。<br>注意while 的分号；位置，while也是一个单独语句。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// while2.c -- 注意分号位置</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n=<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (n++&lt;<span class="number">3</span>);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;n is %d \n&quot;</span>,n);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">n is 4</span><br></pre></td></tr></table></figure>

<p>利用这种空语句的循环，可以做到：跳过第一个非空白字符或数字。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> (<span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;num) == <span class="number">1</span>)</span><br><span class="line">    ;</span><br><span class="line"><span class="comment">// 跳过整数输入</span></span><br></pre></td></tr></table></figure>

<p>只要输入一个整数，那么条件为真，继续循环读取输入；注意分号最好单独放一行便于理解，但是可以使用continue来更好的处理这种奇葩的情况。</p>
<p><a name="6.3">6.3 用关系运算符和表达式比较大小</a></p>
<p>！= 不等于</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// cmpflt.c -- 浮点数比较</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;math.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">double</span> ANSER = <span class="number">3.14159</span>;</span><br><span class="line">    <span class="keyword">double</span> response;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;PI = ?\n&quot;</span>);</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%lf&quot;</span>, &amp;response);</span><br><span class="line">    <span class="keyword">while</span> (<span class="built_in">fabs</span>(response - ANSER) &gt; <span class="number">0.001</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* code */</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;Try again!\n&quot;</span>);</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%lf&quot;</span>, &amp;response);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;OK!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">PI &#x3D; ?</span><br><span class="line">3.14</span><br><span class="line">Try again!</span><br><span class="line">3.12</span><br><span class="line">Try again!</span><br><span class="line">3.1415</span><br><span class="line">OK!</span><br></pre></td></tr></table></figure>

<p>比较浮点数时尽量只是用大于和小于符号&lt; &gt;,因为浮点数的舍入误差会导致逻辑上应该相等的两数却不相等。使用 math.h 头文件的 fabs() 函数可以方便的比较浮点数的大小。<br>真假值：非0值就是真，0为假<br>所以可以简写条件语句：<br>while(goats!=0);<br>为：<br>while(goats);</p>
<ul>
<li><p>新的_Bool 类型</p>
<p>_Bool 类型的变量只能存储1（真）或0（假），如果把其他非零数值赋给 _Bool 类型的变量，该变量会被设置为1，这反映了C把所有非零值都视为真。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// boolean.c -- 使用_Bool 类型的变量</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">long</span> num;</span><br><span class="line">    <span class="keyword">long</span> sum = <span class="number">0L</span>;</span><br><span class="line">    <span class="keyword">bool</span> input_is_good;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;please enter an integer to be sum:\n&quot;</span>);</span><br><span class="line">    input_is_good = <span class="built_in">scanf</span>(<span class="string">&quot;%ld&quot;</span>, &amp;num) == <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span> (input_is_good)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* code */</span></span><br><span class="line">        sum = sum + num;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;please enter an integer to be sum:\n&quot;</span>);</span><br><span class="line">        input_is_good = <span class="built_in">scanf</span>(<span class="string">&quot;%ld&quot;</span>, &amp;num) == <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;sum = %ld\n&quot;</span>,sum);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">please enter an integer to be sum:</span><br><span class="line">12</span><br><span class="line">please enter an integer to be sum:</span><br><span class="line">21</span><br><span class="line">please enter an integer to be sum:</span><br><span class="line">q</span><br><span class="line">sum &#x3D; 33</span><br></pre></td></tr></table></figure>

<p>这里我使用的是 bool 才可以。如果不支持可以使用C99的 stdbool.h 头文件，让头文件让 bool 成为 _Bool  的别名，或者使用int替换。</p>
</li>
</ul>
<p><a name="6.4">6.4 不确定循环和计数循环</a></p>
<p>是否确定循环次数？<br>计数循环：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sweetie1.c -- 计数循环</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> NUMBER = <span class="number">22</span>;</span><br><span class="line">    <span class="keyword">int</span> count = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span> (count&lt;=NUMBER)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* code */</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;Go!\n&quot;</span>);</span><br><span class="line">        count++;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><a name="6.5">6.5 for循环</a></p>
<p>但是这种写法比较low，容易忘记初始化计数器，看看下面的for循环：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// sweetie2.c -- 使用for循环的计数循环</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> NUMBER = <span class="number">22</span>;</span><br><span class="line">    <span class="keyword">int</span> count;</span><br><span class="line">    <span class="keyword">for</span>(count=<span class="number">1</span>;count&lt;=NUMBER;count++)&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;Go! %d\n&quot;</span>,count);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">Go! 1</span><br><span class="line">Go! 2</span><br><span class="line">Go! 3</span><br><span class="line">Go! 4</span><br><span class="line">Go! 5</span><br><span class="line">Go! 6</span><br><span class="line">Go! 7</span><br><span class="line">Go! 8</span><br><span class="line">Go! 9</span><br><span class="line">Go! 10</span><br><span class="line">Go! 11</span><br><span class="line">Go! 12</span><br><span class="line">Go! 13</span><br><span class="line">Go! 14</span><br><span class="line">Go! 15</span><br><span class="line">Go! 16</span><br><span class="line">Go! 17</span><br><span class="line">Go! 18</span><br><span class="line">Go! 19</span><br><span class="line">Go! 20</span><br><span class="line">Go! 21</span><br><span class="line">Go! 22</span><br></pre></td></tr></table></figure>

<p>for后面的圆括号有3个表达式，分别用两个分号分隔，第一个表达式是初始化，只会在for循环开始的时候执行一次，第二个表达式是测试条件，在执行循环前先对表达式求值，如果条件表达式为假，循环结束。第三个表达式执行更新，for中的表达式都是完整的表达式，所以每个表达式的副作用（如：递增变量即改变变量的值）都会在下一条表达式之前生效。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// for_cude.c -- for 循环创建一个立方表</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> num;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;    n   cubed\n&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span>(num=<span class="number">1</span>;num&lt;=<span class="number">6</span>;num++)&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%5d %5d\n&quot;</span>,num,num*num*num);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">n   cubed</span><br><span class="line"> 1     1</span><br><span class="line"> 2     8</span><br><span class="line"> 3    27</span><br><span class="line"> 4    64</span><br><span class="line"> 5   125</span><br><span class="line"> 6   216</span><br></pre></td></tr></table></figure>

<p>接下来看看for的其他用法：</p>
<ul>
<li>递减运算符</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// for_down.c </span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> secs;</span><br><span class="line">    <span class="keyword">for</span>(secs = <span class="number">5</span>;secs&gt;<span class="number">0</span>;secs--)&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%d seconds!\n&quot;</span>,secs);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;OK!\n&quot;</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">5 seconds!</span><br><span class="line">4 seconds!</span><br><span class="line">3 seconds!</span><br><span class="line">2 seconds!</span><br><span class="line">1 seconds!</span><br><span class="line">OK!</span><br></pre></td></tr></table></figure>

<ul>
<li>计数器递增数字可以任意改变</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// for_13s.c</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n;</span><br><span class="line">    <span class="keyword">for</span> (n = <span class="number">2</span>; n &lt; <span class="number">60</span>; n = n + <span class="number">13</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* code */</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%d \n&quot;</span>, n);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">2</span><br><span class="line">15</span><br><span class="line">28</span><br><span class="line">41</span><br><span class="line">54</span><br></pre></td></tr></table></figure>

<ul>
<li>可以用字符代替数字计数</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// for_char.c</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">char</span> ch;</span><br><span class="line">    <span class="keyword">for</span> (ch = <span class="string">&#x27;a&#x27;</span>; ch &lt;= <span class="string">&#x27;z&#x27;</span>; ch++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* code */</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;The ASCII value for %c is %d\n&quot;</span>,ch,ch);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">The ASCII value for a is 97</span><br><span class="line">The ASCII value for b is 98</span><br><span class="line">The ASCII value for c is 99</span><br><span class="line">The ASCII value for d is 100</span><br><span class="line">The ASCII value for e is 101</span><br><span class="line">The ASCII value for f is 102</span><br><span class="line">The ASCII value for g is 103</span><br><span class="line">The ASCII value for h is 104</span><br><span class="line">The ASCII value for i is 105</span><br><span class="line">The ASCII value for j is 106</span><br><span class="line">The ASCII value for k is 107</span><br><span class="line">The ASCII value for l is 108</span><br><span class="line">The ASCII value for m is 109</span><br><span class="line">The ASCII value for n is 110</span><br><span class="line">The ASCII value for o is 111</span><br><span class="line">The ASCII value for p is 112</span><br><span class="line">The ASCII value for q is 113</span><br><span class="line">The ASCII value for r is 114</span><br><span class="line">The ASCII value for s is 115</span><br><span class="line">The ASCII value for t is 116</span><br><span class="line">The ASCII value for u is 117</span><br><span class="line">The ASCII value for v is 118</span><br><span class="line">The ASCII value for w is 119</span><br><span class="line">The ASCII value for x is 120</span><br><span class="line">The ASCII value for y is 121</span><br><span class="line">The ASCII value for z is 122</span><br></pre></td></tr></table></figure>

<ul>
<li>可以省略一个或多个表达式，只要在循环中包含结束循环的语句即可。</li>
<li>第一个表达式不一定是给变量赋值，也可以使用printf() 语句，但是记住这个表达式只能执行一次。</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// for_show.c</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> num =<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="built_in">printf</span>(<span class="string">&quot;Keep going!\n&quot;</span>);num!=<span class="number">6</span>;)&#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>,&amp;num);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;This is right!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Keep going!</span><br><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">56</span><br><span class="line">6</span><br><span class="line">This is right!</span><br></pre></td></tr></table></figure>

<p><a name="6.6">6.6 其他赋值运算符</a></p>
<p>简写运算符，注意优先级。</p>
<p><a name="6.7">6.7 逗号运算符</a></p>
<p>逗号运算符扩展了for循环的灵活性，例如：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// postage.c -- 一类邮资</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> FIRST_OZ = <span class="number">46</span>;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> NEXT_OZ = <span class="number">20</span>;</span><br><span class="line">    <span class="keyword">int</span> ounces, cost;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;ounces  cost\n&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span> (ounces = <span class="number">1</span>, cost = FIRST_OZ; ounces &lt;= <span class="number">16</span>; ounces++, cost += NEXT_OZ)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%5d $%4.2f\n&quot;</span>, ounces, cost / <span class="number">100.0</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">ounces  cost</span><br><span class="line">    1 $0.46</span><br><span class="line">    2 $0.66</span><br><span class="line">    3 $0.86</span><br><span class="line">    4 $1.06</span><br><span class="line">    5 $1.26</span><br><span class="line">    6 $1.46</span><br><span class="line">    7 $1.66</span><br><span class="line">    8 $1.86</span><br><span class="line">    9 $2.06</span><br><span class="line">   10 $2.26</span><br><span class="line">   11 $2.46</span><br><span class="line">   12 $2.66</span><br><span class="line">   13 $2.86</span><br><span class="line">   14 $3.06</span><br><span class="line">   15 $3.26</span><br><span class="line">   16 $3.46</span><br></pre></td></tr></table></figure>

<p>该程序在初始化表达式和更新表达式中使用了逗号运算符。逗号的存在让两个变量都初始化了，以及更新表达式有了的两个改变。<br>逗号运算符有两个性质：</p>
<ol>
<li>首先，它保证了被它分隔的表达式从左往右求值，因为逗号就是一个序列点，所以逗号左侧项的所有副作用都在程序执行逗号右侧前生效。</li>
<li>注意不要犯这样的错误：</li>
</ol>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">num = <span class="number">249</span>, <span class="number">500</span>;</span><br></pre></td></tr></table></figure>

<p>因为这样等于</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> mice, num;</span><br><span class="line">    num = <span class="number">249</span>, <span class="number">500</span>;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>,num);</span><br><span class="line"></span><br><span class="line">    num = <span class="number">249</span>;</span><br><span class="line">    <span class="number">500</span>;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>,num);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">249</span><br><span class="line">249</span><br></pre></td></tr></table></figure>

<p><a name="6.8">6.8 出口条件循环do while</a></p>
<p>for 和 while 循环都是入口条件循环，在迭代之前检查测试条件，do while 是出口条件循环，先迭代后检查测试条件，这样至少保证执行一次。有时do while 可以比while 更简洁一些。</p>
<p><a name="6.9">6.9 如何选择循环</a></p>
<p>当循环设计初始化和更新变量时，用for循环比较合适，但是有些情况用while更好，如循环输入：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span>(<span class="built_in">scanf</span>(<span class="string">&quot;%ld&quot;</span>,&amp;num)==<span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<p><a name="6.10">6.10 嵌套循环</a></p>
<p>嵌套循环常用语按行和列显示数据</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// rows1.c -- 使用嵌套循环</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> ROW 6</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> CHARS 10</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> row;</span><br><span class="line">    <span class="keyword">char</span> ch;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(row = <span class="number">0</span>;row&lt;ROW;row++)&#123;</span><br><span class="line">        <span class="keyword">for</span>(ch=<span class="string">&#x27;A&#x27;</span>;ch&lt;(<span class="string">&#x27;A&#x27;</span>+CHARS);ch++)&#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">&quot;%c&quot;</span>,ch);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;\n&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ABCDEFGHIJ</span><br><span class="line">ABCDEFGHIJ</span><br><span class="line">ABCDEFGHIJ</span><br><span class="line">ABCDEFGHIJ</span><br><span class="line">ABCDEFGHIJ</span><br><span class="line">ABCDEFGHIJ</span><br></pre></td></tr></table></figure>

<p>嵌套循环有外层循环和内层循环。每次外层循环迭代要先执行完所有的内层循环才能执行下一个外层循环。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// rows2.c -- 依赖外部循环的嵌套循环</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> ROWS = <span class="number">6</span>;</span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">int</span> CHARS = <span class="number">6</span>;</span><br><span class="line">    <span class="keyword">int</span> row;</span><br><span class="line">    <span class="keyword">char</span> ch;</span><br><span class="line">    <span class="keyword">for</span> (row = <span class="number">0</span>; row &lt; ROWS; row++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">for</span> (ch = (<span class="string">&#x27;A&#x27;</span> + row); ch &lt; (<span class="string">&#x27;A&#x27;</span> + CHARS); ch++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">&quot;%c&quot;</span>, ch);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;\n&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ABCDEF</span><br><span class="line">BCDEF</span><br><span class="line">CDEF</span><br><span class="line">DEF</span><br><span class="line">EF</span><br><span class="line">F</span><br></pre></td></tr></table></figure>

<p>因为每次迭代都要把row的值和’A’ 相加，所以ch在每一行都被初始化为不同的字符，然而，测试条件并没有改变，所以每行依旧是F结尾，这使得每一行打印的字符都比上一行少一个。</p>
<p><a name="6.11">6.11 数据简介</a></p>
<p>循环要经常使用数组。通过整数下标访问数组中单独的元素。声明数组：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">float</span> debts[<span class="number">20</span>];</span><br></pre></td></tr></table></figure>

<p>声明debts是一个含有20个元素的数组，且每个元素都可以存储float类型的值。数组元素的编号从0开始。使用数组元素和使用同类型的变量一样，例如可以这样把值读入指定的元素中。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">scanf</span>(<span class="string">&quot;%f&quot;</span>,&amp;debts[<span class="number">4</span>]);</span><br></pre></td></tr></table></figure>

<p>注意取地址符 &amp;</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// scores_in.c -- 使用循环处理数组</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SIZE 10</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> PAR 72</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> index, score[SIZE];</span><br><span class="line">    <span class="keyword">int</span> sum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">float</span> average;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;输入 %d 高尔夫分数:\n&quot;</span>, SIZE);</span><br><span class="line">    <span class="keyword">for</span> (index = <span class="number">0</span>; index &lt; SIZE; index++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;score[index]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (index = <span class="number">0</span>; index &lt; SIZE; index++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* code */</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%5d&quot;</span>,score[index]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(index=<span class="number">0</span>;index&lt;SIZE;index++)&#123;</span><br><span class="line">        sum += score[index];</span><br><span class="line">    &#125;</span><br><span class="line">    average = (<span class="keyword">float</span>)sum/SIZE;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;sum = %d,average = %.2f\n&quot;</span>,sum,average);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;average - PAR = %.0f\n&quot;</span>,average-PAR);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">杈撳叆 10 楂樺皵澶垎鏁?</span><br><span class="line">99 95 109 105 100</span><br><span class="line">96 98 93 99 97 98</span><br><span class="line">   99   95  109  105  100   96   98   93   99   97</span><br><span class="line">sum &#x3D; 991,average &#x3D; 99.10</span><br><span class="line">average - PAR &#x3D; 27</span><br></pre></td></tr></table></figure>

<p>虽然输入了11个数字，但是由于循环只读取10个数字，剩下一个便去了缓冲区。输入以空白分隔。<br>复现输入结果的编程习惯不错</p>
<p><a name="6.12">6.12 使用函数返回值的循环示例</a></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// power.c -- 计算数的整数幂</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">double</span> <span class="title">power</span><span class="params">(<span class="keyword">double</span> n, <span class="keyword">int</span> p)</span></span>; <span class="comment">// ANSI 函数原型</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> <span class="keyword">const</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">double</span> x, xpow;</span><br><span class="line">    <span class="keyword">int</span> <span class="built_in">exp</span>;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;输入底数和指数：\n&quot;</span>);</span><br><span class="line">    <span class="keyword">while</span> (<span class="built_in">scanf</span>(<span class="string">&quot;%lf%d&quot;</span>, &amp;x, &amp;<span class="built_in">exp</span>) == <span class="number">2</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* code */</span></span><br><span class="line">        xpow = power(x, <span class="built_in">exp</span>);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%.3g 为底，%d 为指数 的结果是 %.5g\n&quot;</span>, x, <span class="built_in">exp</span>, xpow);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;OK!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">double</span> <span class="title">power</span><span class="params">(<span class="keyword">double</span> n, <span class="keyword">int</span> p)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">double</span> <span class="built_in">pow</span> = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">1</span>; i &lt;= p; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">pow</span> *= n;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">pow</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">输入底数和指数：</span><br><span class="line">1.2 12</span><br><span class="line">1.2 为底，12 为指数 的结果是 8.9161</span><br><span class="line">2</span><br><span class="line">16</span><br><span class="line">2 为底，16 为指数 的结果是 65536</span><br><span class="line">q</span><br><span class="line">OK!</span><br></pre></td></tr></table></figure>

<p>scanf() 若成功读取两个值就返回2；函数可以先声明再定义。</p>
<p><a name="6.13">6.13 关键概念</a></p>
<p><a name="6.14">6.14 本章小结</a></p>
<p><a name="6.15">6.15 复习题</a></p>
<p>数组名就是地址，scanf() 使用时不用加取地址符 &amp;</p>

  
  
    
    <div class='footer'>
      
      
      
        <div class='copyright'>
          <blockquote>
            
              
                <p>博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</p>

              
            
              
                <p>本文永久链接是：<a href=https://hardydragon.gitee.io/blog/2021/03/22/%E7%AC%AC%E5%85%AD%E7%AB%A0C%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%BE%AA%E7%8E%AF/>https://hardydragon.gitee.io/blog/2021/03/22/%E7%AC%AC%E5%85%AD%E7%AB%A0C%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%BE%AA%E7%8E%AF/</a></p>
              
            
          </blockquote>
        </div>
      
      
    </div>
  
  
    


  <div class='article-meta' id="bottom">
    <div class='new-meta-box'>
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2021-03-22T23:02:24+08:00">
  <a class='notlink'>
    <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
    <p>更新于：2021年3月22日</p>
  </a>
</div>

        
      
        
          
  
  <div class="new-meta-item meta-tags"><a class="tag" href="/blog/tags/C-Notes/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>C Notes</p></a></div>


        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://hardydragon.gitee.io/blog/2021/03/22/%E7%AC%AC%E5%85%AD%E7%AB%A0C%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%BE%AA%E7%8E%AF/&title=第六章 C控制语句：循环 - HardyDragon Index&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" srcset="">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://hardydragon.gitee.io/blog/2021/03/22/%E7%AC%AC%E5%85%AD%E7%AB%A0C%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%BE%AA%E7%8E%AF/&title=第六章 C控制语句：循环 - HardyDragon Index&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" srcset="">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="http://service.weibo.com/share/share.php?url=https://hardydragon.gitee.io/blog/2021/03/22/%E7%AC%AC%E5%85%AD%E7%AB%A0C%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%BE%AA%E7%8E%AF/&title=第六章 C控制语句：循环 - HardyDragon Index&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" srcset="">
          
        </a>
      
    
      
    
      
    
  </div>
</div>



        
      
    </div>
  </div>


  
  

  
    <div class="prev-next">
      
        <a class='prev' href='/blog/2021/03/22/%E7%AC%AC%E4%B9%9D%E7%AB%A0%E5%87%BD%E6%95%B0/'>
          <p class='title'><i class="fas fa-chevron-left" aria-hidden="true"></i>第九章 函数</p>
          <p class='content'>第九章 函数
函数原型即函数声明，函数调用，函数定义即明确指定函数要做什么。

有些老编译器识别不了void返回值的函数，需要改为int。

如果函数放到其他文件需要导入

局部变量和全局变量
...</p>
        </a>
      
      
        <a class='next' href='/blog/2021/03/22/%E7%AC%AC%E4%B8%83%E7%AB%A0C%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%88%86%E6%94%AF%E5%92%8C%E8%B7%B3%E8%BD%AC/'>
          <p class='title'>第七章 C控制语句：分支和跳转<i class="fas fa-chevron-right" aria-hidden="true"></i></p>
          <p class='content'>第七章 C控制语句：分支和跳转7.1 if语句7.2 if else语句7.2.1 介绍getchar()7.2.2 ctype.h 系列的字符函数7.2.3 多重选择else if7.2.4 ...</p>
        </a>
      
    </div>
  
</article>


  

  <article class="post white-box reveal shadow" id="comments">
    <p ct><i class='fas fa-comments'></i> 评论</p>
    
    <div id="valine_container" class="valine_thread">
  <i class="fas fa-cog fa-spin fa-fw fa-2x"></i>
</div>

  </article>






</div>
<aside class='l_side'>
  
  
    
    



  <section class="widget toc-wrapper shadow desktop mobile" id="toc-div" >
    
  <header>
    
      <i class="fas fa-list fa-fw" aria-hidden="true"></i><span class='name'>本文目录</span>
    
  </header>


    <div class='content'>
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#6-1-%E5%86%8D%E6%8E%A2while%E5%BE%AA%E7%8E%AF"><span class="toc-text">6.1 再探while循环</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%A8%8B%E5%BA%8F%E6%B3%A8%E9%87%8A"><span class="toc-text">程序注释</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#C%E9%A3%8E%E6%A0%BC%E8%AF%BB%E5%8F%96%E5%BE%AA%E7%8E%AF"><span class="toc-text">C风格读取循环</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-2-while%E8%AF%AD%E5%8F%A5"><span class="toc-text">6.2 while语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-1-%E7%BB%88%E6%AD%A2while%E5%BE%AA%E7%8E%AF"><span class="toc-text">6.2.1 终止while循环</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%95%E6%97%B6%E7%BB%88%E6%AD%A2%E5%BE%AA%E7%8E%AF"><span class="toc-text">何时终止循环</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#while%EF%BC%9A%E5%85%A5%E5%8F%A3%E6%9D%A1%E4%BB%B6%E5%BE%AA%E7%8E%AF"><span class="toc-text">while：入口条件循环</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%AD%E6%B3%95%E8%A6%81%E7%82%B9"><span class="toc-text">语法要点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-3-%E7%94%A8%E5%85%B3%E7%B3%BB%E8%BF%90%E7%AE%97%E7%AC%A6%E5%92%8C%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%AF%94%E8%BE%83%E5%A4%A7%E5%B0%8F"><span class="toc-text">6.3 用关系运算符和表达式比较大小</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-1-%E4%BB%80%E4%B9%88%E6%98%AF%E7%9C%9F"><span class="toc-text">6.3.1 什么是真</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-2-%E5%85%B6%E4%BB%96%E7%9C%9F%E5%80%BC"><span class="toc-text">6.3.2 其他真值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-3-%E7%9C%9F%E5%80%BC%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-text">6.3.3 真值的问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-4-%E6%96%B0%E7%9A%84-Bool-%E7%B1%BB%E5%9E%8B"><span class="toc-text">6.3.4 新的_Bool 类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-5-%E4%BC%98%E5%85%88%E7%BA%A7%E5%92%8C%E5%85%B3%E7%B3%BB%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">6.3.5 优先级和关系运算符</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-4-%E4%B8%8D%E7%A1%AE%E5%AE%9A%E5%BE%AA%E7%8E%AF%E5%92%8C%E8%AE%A1%E6%95%B0%E5%BE%AA%E7%8E%AF"><span class="toc-text">6.4 不确定循环和计数循环</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-5-for%E5%BE%AA%E7%8E%AF"><span class="toc-text">6.5 for循环</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-6-%E5%85%B6%E4%BB%96%E8%B5%8B%E5%80%BC%E8%BF%90%E7%AE%97%E7%AC%A6%EF%BC%9A-%E3%80%81-%E3%80%81-%E3%80%81-%E3%80%81"><span class="toc-text">6.6 其他赋值运算符： +&#x3D; 、-&#x3D;、*&#x3D;、&#x2F;&#x3D;、%&#x3D;</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-7-%E9%80%97%E5%8F%B7%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-text">6.7 逗号运算符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-8-%E5%87%BA%E5%8F%A3%E6%9D%A1%E4%BB%B6%E5%BE%AA%E7%8E%AF%EF%BC%9Ado-while"><span class="toc-text">6.8 出口条件循环：do while</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-9-%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9%E5%BE%AA%E7%8E%AF"><span class="toc-text">6.9 如何选择循环</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-10-%E5%B5%8C%E5%A5%97%E5%BE%AA%E7%8E%AF"><span class="toc-text">6.10 嵌套循环</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-10-1-%E7%A8%8B%E5%BA%8F%E5%88%86%E6%9E%90"><span class="toc-text">6.10.1 程序分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-10-2-%E5%B5%8C%E5%A5%97%E5%8F%98%E5%BC%8F"><span class="toc-text">6.10.2 嵌套变式</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-11-%E6%95%B0%E7%BB%84%E7%AE%80%E4%BB%8B"><span class="toc-text">6.11 数组简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-12-%E4%BD%BF%E7%94%A8%E5%87%BD%E6%95%B0%E8%BF%94%E5%9B%9E%E5%80%BC%E7%9A%84%E5%BE%AA%E7%8E%AF%E7%A4%BA%E4%BE%8B"><span class="toc-text">6.12 使用函数返回值的循环示例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-12-1-%E7%A8%8B%E5%BA%8F%E5%88%86%E6%9E%90"><span class="toc-text">6.12.1 程序分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-12-2-%E4%BD%BF%E7%94%A8%E5%B8%A6%E8%BF%94%E5%9B%9E%E5%80%BC%E7%9A%84%E5%87%BD%E6%95%B0"><span class="toc-text">6.12.2 使用带返回值的函数</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-13-%E5%85%B3%E9%94%AE%E6%A6%82%E5%BF%B5"><span class="toc-text">6.13 关键概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-14-%E6%9C%AC%E7%AB%A0%E5%B0%8F%E7%BB%93"><span class="toc-text">6.14 本章小结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-15-%E5%A4%8D%E4%B9%A0%E9%A2%98"><span class="toc-text">6.15 复习题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-16-%E7%BC%96%E7%A8%8B%E7%BB%83%E4%B9%A0"><span class="toc-text">6.16 编程练习</span></a></li></ol>
    </div>
  </section>


  


</aside>



        
      </div>
      
  
  <footer class="footer clearfix">
    <br><br>
    
      
        <div class="aplayer-container">
          

  
    <meting-js
      theme='#1BCDFC'
      autoplay='false'
      volume='0.7'
      loop='all'
      order='list'
      fixed='true'
      list-max-height='320px'
      server='netease'
      type='playlist'
      id='3175833810'
      list-folded='true'>
    </meting-js>
  


        </div>
      
    
      
        <br>
        <div class="social-wrapper">
          
            
          
            
          
            
              <a href="https://gitee.com/hardychenlong"
                class="social fab fa-gitee flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
                
              </a>
            
          
            
          
        </div>
      
    
      
        <div><p>博客内容遵循 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</a></p>
</div>
      
    
      
        本站使用
        <a href="https://github.com/volantis-x/hexo-theme-volantis/tree/4.0.0" target="_blank" class="codename">Volantis</a>
        作为主题
      
    
      
        <div class='copyright'>
        <p><a target="_blank" rel="noopener" href="https://hardydragon.io/">Copyright © 2020-2021 HardyDragon</a></p>

        </div>
      
    
  </footer>


      <a class="s-top fas fa-arrow-up fa-fw" href='javascript:void(0)'></a>
    </div>
  </div>
  <div>
    <!-- required -->

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5/dist/jquery.min.js"></script>

<script>
  function pjax_fancybox() {
    $(".md .gallery").find("img").each(function () { //渲染 fancybox
      var element = document.createElement("a"); // a 标签
      $(element).attr("class", "fancybox");
      $(element).attr("pjax-fancybox", "");  // 过滤 pjax
      $(element).attr("href", $(this).attr("src"));
      if ($(this).attr("data-original")) {
        $(element).attr("href", $(this).attr("data-original"));
      }
      $(element).attr("data-fancybox", "images");
      var caption = "";   // 描述信息
      if ($(this).attr('alt')) {  // 判断当前页面是否存在描述信息
        $(element).attr('data-caption', $(this).attr('alt'));
        caption = $(this).attr('alt');
      }
      var div = document.createElement("div");
      $(div).addClass("fancybox");
      $(this).wrap(div); // 最外层套 div ，其实主要作用还是 class 样式
      var span = document.createElement("span");
      $(span).addClass("image-caption");
      $(span).text(caption); // 加描述
      $(this).after(span);  // 再套一层描述
      $(this).wrap(element);  // 最后套 a 标签
    })
    $(".md .gallery").find("img").fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: false,
      closeClick: true,
      helpers: {
        overlay: {closeClick: true}
      },
      buttons: [
        "zoom",
        "close"
      ]
    });
  };
  function SCload_fancybox() {
    if ($(".md .gallery").find("img").length == 0) return;
    loadCSS("https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css", document.getElementById("loadcss"));
    setTimeout(function() {
      loadScript('https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js', pjax_fancybox)
    }, 1);
  };
  $(function () {
    SCload_fancybox();
  });
</script>


<!-- internal -->

  
  
  
    
<script src="https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js"></script>

    <script type="text/javascript">
      $(function(){
        var imgs=["https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/001.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/002.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/003.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/004.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/005.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/006.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/012.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/016.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/019.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/025.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/033.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/034.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/035.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/038.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/039.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/042.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/046.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/051.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/052.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/054.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/056.jpg"];
        if ('true' == 'true') {
          function shuffle(arr){
            /*From countercurrent-time*/
            var n = arr.length;
            while(n--) {
              var index = Math.floor(Math.random() * n);
              var temp = arr[index];
              arr[index] = arr[n];
              arr[n] = temp;
            }
          }
          shuffle(imgs);
        }
        if ('.cover-backstretch') {
          $('.cover-backstretch').backstretch(
            imgs,
          {
            duration: "10000",
            fade: "1500"
          });
        } else {
          $.backstretch(
            imgs,
          {
            duration: "10000",
            fade: "1500"
          });
        }
      });
    </script>
  







  <script defer src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script>
<script>
  // https://www.npmjs.com/package/vanilla-lazyload
  // Set the options globally
  // to make LazyLoad self-initialize
  window.lazyLoadOptions = {
    elements_selector: ".lazyload",
    threshold: 0
  };
  // Listen to the initialization event
  // and get the instance of LazyLoad
  window.addEventListener(
    "LazyLoad::Initialized",
    function (event) {
      window.lazyLoadInstance = event.detail.instance;
    },
    false
  );
  document.addEventListener('DOMContentLoaded', function () {
    lazyLoadInstance.update();
  });
  document.addEventListener('pjax:complete', function () {
    lazyLoadInstance.update();
  });
</script>




  
  
    <script>
      window.FPConfig = {
        delay: 0,
        ignoreKeywords: [],
        maxRPS: 5,
        hoverDelay: 25
      };
    </script>
    <script defer src="https://cdn.jsdelivr.net/gh/gijo-varghese/flying-pages@2.1.2/flying-pages.min.js"></script>
  




  <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
    var clipboard = new ClipboardJS('.btn-copy', {
        target: function (trigger) {
            return trigger.nextElementSibling
        }
    });
    function wait(callback, seconds) {
        var timelag = null;
        timelag = window.setTimeout(callback, seconds)
    }
    function pjax_initCopyCode() {
		if($(".highlight .code pre").length+$(".article pre code").length==0)return;
        var copyHtml = '';
        copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
        copyHtml += '<i class="fas fa-copy"></i><span>COPY</span>';
        copyHtml += '</button>';
        $(".highlight .code pre").before(copyHtml);
        $(".article pre code").before(copyHtml);
        clipboard.off('success').on('success', function (e) {
            let $btn = $(e.trigger);
            $btn.addClass('copied');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-check-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPIED';
            wait(function () {
                $icon.removeClass('fa-check-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        });
        clipboard.off('error').on('error', function (e) {
            e.clearSelection();
            let $btn = $(e.trigger);
            $btn.addClass('copy-failed');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-times-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPY FAILED';
            wait(function () {
                $icon.removeClass('fa-times-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        })
    }
    $(function () {
        pjax_initCopyCode()
    });
</script>




   <script src="https://cdn.jsdelivr.net/npm/scrollreveal@4.0.6/dist/scrollreveal.min.js"></script>
<script type="text/javascript">
  function pjax_scrollrebeal() {
    ScrollReveal().reveal('.l_main .reveal', {
      distance: '32px',
      duration: '800',
      interval: '20',
      scale: '1',
      easing: 'ease-out'
    });
  }
  $(function () {
    pjax_scrollrebeal();
  });
</script>




  <script>
  let APlayerController = new Object();
  APlayerController.id = '3175833810';  // 设定全局音乐播放ID
  APlayerController.volume = '0.7';
</script>

  
<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10/dist/APlayer.min.js"></script>


  
<script src="https://cdn.jsdelivr.net/npm/meting@2.0/dist/Meting.min.js"></script>








  
  
<script src="/blog/js/valine.js"></script>


<script>
  var GUEST_INFO = ['nick', 'mail', 'link'];
  var meta = 'nick,mail,link'.split(',').filter(function (item) {
    return GUEST_INFO.indexOf(item) > -1
  });
  var REQUIRED_FIELDS = ['nick', 'mail', 'link'];
  var requiredFields = 'nick,mail'.split(',').filter(function (item) {
    return REQUIRED_FIELDS.indexOf(item) > -1
  });

  function emoji(path, idx, ext) {
    return path + "/" + path + "-" + idx + "." + ext;
  }

  var emojiMaps = {};
  for (var i = 1; i <= 54; i++) {
    emojiMaps['tieba-' + i] = emoji('tieba', i, 'png');
  }
  for (var i = 1; i <= 101; i++) {
    emojiMaps['qq-' + i] = emoji('qq', i, 'gif');
  }
  for (var i = 1; i <= 116; i++) {
    emojiMaps['aru-' + i] = emoji('aru', i, 'gif');
  }
  for (var i = 1; i <= 125; i++) {
    emojiMaps['twemoji-' + i] = emoji('twemoji', i, 'png');
  }
  for (var i = 1; i <= 4; i++) {
    emojiMaps['weibo-' + i] = emoji('weibo', i, 'png');
  }

  function pjax_valine() {
    if(!document.querySelectorAll("#valine_container")[0])return;

    let pagePlaceholder = $.trim($('#pjax-comment-placeholder').text()) || "快来评论吧~";

    let path = $.trim($('#pjax-comment-path').text());
    if (path.length == 0) {
      let defaultPath = '';
      path = defaultPath || decodeURI(window.location.pathname);
    }

    var valine = new Valine();
    valine.init({
      el: '#valine_container',
      meta: meta,
      placeholder: pagePlaceholder,
      path: path,
      appId: "",
      appKey: "",
      pageSize: '10',
      avatar: 'robohash',
      lang: 'zh-cn',
      visitor: 'true',
      highlight: 'true',
      mathJax: 'false',
      enableQQ: 'true',
      recordIP: false,
      requiredFields: requiredFields,
      emojiCDN: 'https://cdn.jsdelivr.net/gh/volantis-x/cdn-emoji/valine/',
      emojiMaps: emojiMaps
    })
  }

  $(function () {
    pjax_valine();
  });
</script>




  
<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5/lib/darkmode-js.min.js" aysc></script>

<script type="text/javascript">
function getClientHeight(){
  var clientHeight=0;
  if(document.body.clientHeight&&document.documentElement.clientHeight){
  var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }else{
  var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }
  return clientHeight;
}
function supportCss3(style) {
  var prefix = ['webkit', 'Moz', 'ms', 'o'],
  i,
  humpString = [],
  htmlStyle = document.documentElement.style,
  _toHumb = function (string) {
  return string.replace(/-(\w)/g, function ($0, $1) {
  return $1.toUpperCase();
  });
  };
  for (i in prefix)
  humpString.push(_toHumb(prefix[i] + '-' + style));
  humpString.push(_toHumb(style));
  for (i in humpString)
  if (humpString[i] in htmlStyle) return true;
  return false;
};
//配置信息
var options = {
  bottom: '60px',
  right: 'unset',
  left: '1400px',
  time: '0s',
  mixColor: '#f4f4f4',
  backgroundColor: '#f4f4f4',
  buttonColorDark: '#333',
  buttonColorLight: '#ddd',
  saveInCookies: true,
  label: '',
  autoMatchOsTheme: true
};
// 卡片兼容处理 mix-blend-mode 与 effect: [blur] 冲突

function pjax_darkmodejs(){
  
  if(!supportCss3('mix-blend-mode'))return;
  var checkExist2 = setInterval(function() {
     if (typeof jQuery == 'undefined'){return;}
     clearInterval(checkExist2);
     var TopFlag=getClientHeight();
    $(window).scroll(function(){
      var top = $(document).scrollTop();
      if(top > TopFlag) {
        $(".darkmode-layer").css("mix-blend-mode","normal");
        $(".darkmode-layer").css("background-color","#222");
      }else{
        $(".darkmode-layer").css("mix-blend-mode","difference");
        $(".darkmode-layer").css("background-color","");
      }
    })
  }, 100);
  
}
// mix-blend-mode support?
if(supportCss3('mix-blend-mode')){
  window.darkmode = new Darkmode(options);
  
  window.darkmode.showWidget();
  
  pjax_darkmodejs();
}
////////////////Development///////////////////////
//////////////darkmode模式切换////////////////////
//window.darkmode.toggle();                     //
//////////////darkmode模式判断////////////////////
//console.log(window.darkmode.isActivated())    //
//////////////////////////////////////////////////
</script>





  
<script src="/blog/js/app.js"></script>




  
    
<script src="/blog/js/search.js"></script>

  


<!-- optional -->

  <script>
const SearchServiceimagePath="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@master/img/";
const ROOT =  ("/blog/" || "/").endsWith('/') ? ("/blog/" || "/") : ("/blog//" || "/" );
(function ($) {
  
    customSearch = new HexoSearch({
      imagePath: SearchServiceimagePath
    });
  
})(jQuery);

</script>





  
<script src="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.js"></script>

  <script type="text/javascript">
    $(function () {
      Waves.attach('.flat-btn', ['waves-button']);
      Waves.attach('.float-btn', ['waves-button', 'waves-float']);
      Waves.attach('.float-btn-light', ['waves-button', 'waves-float', 'waves-light']);
      Waves.attach('.flat-box', ['waves-block']);
      Waves.attach('.float-box', ['waves-block', 'waves-float']);
      Waves.attach('.waves-image');
      Waves.init();
    });
  </script>



  
<script src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@2/js/comment_typing.js"></script>




  
    
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.18.1/build/highlight.min.js"></script>

    <script>hljs.initHighlightingOnLoad();</script>
  



  <script defer>

  const LCCounter = {
    app_id: 'u9j57bwJod4EDmXWdxrwuqQT-MdYXbMMI',
    app_key: 'jfHtEKVE24j0IVCGHbvuFClp',
    custom_api_server: '',

    // 查询存储的记录
    getRecord(Counter, url, title) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({url})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {url, title: title, times: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    },

    // 发起自增请求
    increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    },

    // 构建自增请求体
    buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "times": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    },

    // 校验是否为有效的 UV
    validUV() {
      var key = 'LeanCloudUVTimestamp';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    },

    addCount(Counter) {
      var enableIncr = '' === 'true' && window.location.hostname !== 'localhost';
      enableIncr = true;
      var getterArr = [];
      var incrArr = [];
      // 请求 PV 并自增
      var pvCtn = document.querySelector('#lc-sv');
      if (pvCtn || enableIncr) {
        var pvGetter = this.getRecord(Counter, 'https://hardydragon.gitee.io/blog' + '/#lc-sv', 'Visits').then((record) => {
          incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-sv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + 1;
              if (pvCtn) {
                pvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#lc-uv');
      if (uvCtn || enableIncr) {
        var uvGetter = this.getRecord(Counter, 'https://hardydragon.gitee.io/blog' + '/#lc-uv', 'Visitors').then((record) => {
          var vuv = this.validUV();
          vuv && incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-uv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + (vuv ? 1 : 0);
              if (uvCtn) {
                uvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(uvGetter);
      }

      // 请求文章的浏览数，如果是当前页面就自增
      var allPV = document.querySelectorAll('#lc-pv');
      if (allPV.length > 0 || enableIncr) {
        for (i = 0; i < allPV.length; i++) {
          let pv = allPV[i];
          let title = pv.getAttribute('data-title');
          var url = 'https://hardydragon.gitee.io/blog' + pv.getAttribute('data-path');
          if (url) {
            var viewGetter = this.getRecord(Counter, url, title).then((record) => {
              // 是当前页面就自增
              let curPath = window.location.pathname;
              if (curPath.includes('index.html')) {
                curPath = curPath.substring(0, curPath.lastIndexOf('index.html'));
              }
              if (pv.getAttribute('data-path') == curPath) {
                incrArr.push(this.buildIncrement(record.objectId));
              }
              if (pv) {
                var ele = pv.querySelector('#lc-pv #number');
                if (ele) {
                  if (pv.getAttribute('data-path') == curPath) {
                    ele.innerText = (record.times || 0) + 1;
                  } else {
                    ele.innerText = record.times || 0;
                  }
                  pv.style.display = 'inline';
                }
              }
            });
            getterArr.push(viewGetter);
          }
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && this.increment(Counter, incrArr);
        })
      }

    },


    fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': this.app_id,
            'X-LC-Key': this.app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      this.addCount(Counter);
    },

    refreshCounter() {
      var api_server = this.app_id.slice(-9) !== '-MdYXbMMI' ? this.custom_api_server : `https://${ this.app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;
      if (api_server) {
        this.fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + this.app_id)
          .then(resp => resp.json())
          .then(({api_server}) => {
            this.fetchData('https://' + api_server);
          });
      }
    }

  };

  LCCounter.refreshCounter();

  document.addEventListener('pjax:complete', function () {
    LCCounter.refreshCounter();
  });
</script>



<!-- more -->

  
  <script></script>




    
      


<script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.min.js"></script>

<!-- 样式位于：source/css/_third-party/pjaxanimate.styl -->

<div class="pjax-animate">
  
    <script src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js"></script>
    <div id="loading-bar-wrapper"><script>NProgress.configure({parent:"#loading-bar-wrapper",trickleSpeed: 100})</script></div>
    <script>
      window.ShowLoading = function() {
        NProgress.start();
      };
      window.HideLoading = function() {
        NProgress.done();
      }
    </script>
  
</div>

<script>
    var pjax;
    document.addEventListener('DOMContentLoaded', function () {
      pjax = new Pjax({
        elements: 'a[href]:not([href^="#"]):not([href="javascript:void(0)"]):not([pjax-fancybox])',
        selectors: [
          "title",
          "#pjax-container",
          "#pjax-header-nav-list"
        ],
        cacheBust: false,   // url 地址追加时间戳，用以避免浏览器缓存
        timeout: 5000
      });
    });

    document.addEventListener('pjax:send', function (e) {
      window.stop(); // 相当于点击了浏览器的停止按钮

      try {
        var currentUrl = window.location.pathname;
        var targetUrl = e.triggerElement.href;
        var banUrl = [""];
        if (banUrl[0] != "") {
          banUrl.forEach(item => {
            if(currentUrl.indexOf(item) != -1 || targetUrl.indexOf(item) != -1) {
              window.location.href = targetUrl;
            }
          });
        }
      } catch (error) {}

      window.subData = null; // 移除标题（用于一二级导航栏切换处）
      if (typeof $.fancybox != "undefined") {
        $.fancybox.close();    // 关闭弹窗
      }
      $('.l_header .switcher .s-search').removeClass('active'); // 关闭移动端激活的搜索框
      $('.l_header').removeClass('z_search-open'); // 关闭移动端激活的搜索框
      $('.wrapper').removeClass('sub'); // 跳转页面时关闭二级导航

      // 解绑事件 避免重复监听
      $('.s-top').unbind('click');
      $('.menu a').unbind('click');
      $(window).unbind('resize');
      $(window).unbind('scroll');
      $(document).unbind('scroll');
      $(document).unbind('click');
      $('body').unbind('click');
      window.ShowLoading();
    });

    document.addEventListener('pjax:complete', function () {
      // 关于百度统计对 SPA 页面的处理：
      // 方案一：百度统计>管理>单页应用设置中，打开开启按钮即可对SPA进行统计。 https://tongji.baidu.com/web/help/article?id=324
      // 方案二：取消注释下列代码。 https://tongji.baidu.com/web/help/article?id=235
      // 

      // 关于谷歌统计对 SPA 页面的处理：
      // 当应用以动态方式加载内容并更新地址栏中的网址时，也应该更新通过 gtag.js 存储的网页网址。
      // https://developers.google.cn/analytics/devguides/collection/gtagjs/single-page-applications?hl=zh-cn
      

      $('.nav-main').find('.list-v').not('.menu-phone').removeAttr("style",""); // 移除小尾巴的移除
      $('.menu-phone.list-v').removeAttr("style",""); // 移除小尾巴的移除
      $('script[data-pjax], .pjax-reload script').each(function () {
        $(this).parent().append($(this).remove());
      });
      try{
          if (typeof $.fancybox == "undefined") {
            SCload_fancybox();
          } else {
            pjax_fancybox();
          }
        
          
          if ('.cover-backstretch') {
            $('.cover-backstretch').backstretch("resize");
            if($('.cover-wrapper').is(':hidden')){
              $('.cover-backstretch').backstretch("pause");
            }else{
              $('.cover-backstretch').backstretch("next");
            }
          } else {
            $.backstretch("resize");
            if($('.cover-wrapper').is(':hidden')){
              $.backstretch("pause");
            }else{
              $.backstretch("next");
            }
          }
        
        
        document.querySelectorAll('pre code').forEach((block) => {
          hljs.highlightBlock(block);
        });
        
        
          pjax_scrollrebeal();
        
        
        
          pjax_initCopyCode();
        
        
          pjax_valine();
        
        
        
        
        
          pjax_darkmodejs();
        
      } catch (e) {
        console.log(e);
      }
      window.HideLoading();
    });

    document.addEventListener('pjax:error', function (e) {
      window.HideLoading();
      window.location.href = e.triggerElement.href;
    });
</script>

    
  </div>
</body>
</html>
